/**
 * 
 */
package com.wbl.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

/**
 * @Description:  
 * @version: v1.0.0
 * @author: wbl
 * @date: 2019年8月30日 下午2:49:52
 */
public class DivServerHandler  extends ChannelInboundHandlerAdapter{
	public static Map<String,String> user = new HashMap();//username:on/off_jinbi
	public static List<String> user_group =  new ArrayList();
	public static List<ChannelHandlerContext> user_group_client = new ArrayList();

	 @Override
	    public void channelActive(ChannelHandlerContext ctx) throws Exception {
		 	System.out.println("有新的客户端登录："+ ctx.channel().remoteAddress().toString());
		 	DivChannelInitializer.client_active ++;
	 }
	 
	  @Override
	    public void channelInactive(ChannelHandlerContext ctx) throws Exception {//ctx.close();//close会自动调用本方法
//	        System.out.println("客户端断开链接:" + ctx.channel().remoteAddress().toString());
	        DivChannelInitializer.client_active --;
	        
	        
	        
	  }
		
	    @Override
	    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	    	String body = (String)msg;
	        if("logon".equals(body)){
	        	ctx.channel().writeAndFlush("牛牛客户端登录成功！");
	        	return;
	        }else if(body.contains("wbl1")){//登录
	        	String name = body.substring(4);
	        	if(user.containsKey(name)){
	        		user.put(name, "1_"+yue(name));
	        		ctx.channel().writeAndFlush("wbl1牛气冲天的用户-"+name +"-登录成功！"
	        				+"  账号余额:"+yue(name)
	        				+"  当前在线人数:"+currentOnLine());
		        	return;
	        	}else{
	        		ctx.channel().writeAndFlush("wbl2"+body.substring(4) +"-用户未注册！");
	        		return ;
	        	}
	        }else if(body.contains("wbl2")){//注册
	        	String name = body.substring(4);
	        	if(user.containsKey(name)){
	        		ctx.channel().writeAndFlush("wbl3"+body.substring(4) +"-用户已注册，请换个其他名字！");
		        	return;
	        	}else{
		        	user.put(body.substring(4), "1_20");
		        	
		        	ctx.channel().writeAndFlush("wbl4牛气冲天的用户-"+body.substring(4) +"-注册并登录成功！");
		        	return;
	        	}
	        }else if(body.contains("wbl3")){//开始
	        	String name = body.substring(4);
	        	user_group.add(name);
	        	user_group_client.add(ctx);
	        	
	        	int num = currentOnLine();
	        	if(user_group_client.size() >=2){
	        		String resu = NiuInit.init();
	        		System.out.println("发布游戏结果："+resu);
	        		for(int j = 0;j < user_group_client.size();j++){
	        			ChannelHandlerContext gr = user_group_client.get(j);
	        			gr.channel().writeAndFlush("wbl5" + resu);
	        		}
	        		user_group_client.clear();
	        		user_group.clear();
	        		Thread.sleep(5000);
	        	}
	        	
	        	
	        	
	        	
//	        	for(int j = 0;j < user_group_client.size();j++){
//        			ChannelHandlerContext gr = user_group_client.get(j);
//        			ctx.channel().writeAndFlush("wbl5" + resu);
//        		}
//	        	
//	        	ctx.channel().writeAndFlush("wbl5" + resu);
	        }else if(body.contains("wbl4")){//查询
	        	String name = body.substring(4);
	        	String kvalue = user.get(name);
	        	kvalue = kvalue.substring(2);
	        	ctx.channel().writeAndFlush("wbl6 牛牛用户"+name +"当前帐号余额为:" + kvalue);
	        }else if(body.contains("wbl5")){//退出
	        	String name = body.substring(4);
	        	String kvalue = user.get(name);
	        	user.put(name,"0_"+kvalue.substring(2));
	        }
	        
	        
	        
	    }
	    
	    /**
	     * 超时处理，如果HEARTBEAT_TIME秒没有收到客户端的心跳，就触发; 
	     */
	    /** 空闲次数 */
	    private int idle_count = 1;
	    @Override
	    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
	    	 if (obj instanceof IdleStateEvent) {
		    	 System.out.println("服务端收到xintiao....");
	             IdleStateEvent event = (IdleStateEvent) obj;
	             if (IdleState.READER_IDLE.equals(event.state())) { 
	                 if (idle_count > 2) {
	                     System.out.println("超过两次无客户端请求，关闭该channel");
	                     ctx.channel().close();
	                 }
	                 System.out.println("已等待"+DivChannelInitializer.HEARTBEATTIME
	                		 +DivChannelInitializer.TIME_UNIT
	                		 +"还没收到客户端发来的消息");
	                 idle_count++;
	             }
	         } else {
	             super.userEventTriggered(ctx, obj);
	         }
	    }
	 
	    /**
	     * 当发生异常时，打印异常 日志，释放客户端资源
	     */
	    @Override
	    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	        /**释放资源*/
//	    	ToClientDesign.jedisCluster.hset(ctx.channel().remoteAddress().toString().substring(1),"ONLINE","0");
	        System.out.println("退出游戏！" + cause.getMessage());
	        ctx.close();
	    }
	    
	    //获取当前在线人数
	    public  int currentOnLine(){
	    	int len = 0;
	    	for(String value : user.values()){
//	    	    System.out.println(value);
	    	    if(value.contains("1_")){
	    	    	len ++;
	    	    }
	    	}
	    	return len;
	    }
	    //获取当前用户的金币数
	    public static  String yue(String name){
	    	String value = user.get(name);
	    	String jb = value.substring(2);
	    	return jb;
	    }
	    //写入金币数
	    public static  void write(String name,int mon){
	    	user.put(name, "1_"+mon);
	    }
}
